package com.uenpay.im.ui.old.activity.dynamic;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qyx.android.weight.edittext.EmojisEditText;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.VideoPlayerActivity;
import com.uenpay.im.ui.old.activity.chat.manage.ChatRequestCodeManage;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.weight.ZProgressHUD;
import com.uenpay.smallvideo.MediaRecorderActivity;
import com.uenpay.smallvideo.model.MediaRecorderConfig;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;


/**
 * @Author: SL
 * @Date: 2017/3/1 11:37
 * @CopyRight: http://www.qiyunxin.com
 * @Parameter: TODO
 * @Function: TODO
 */
public class SendDynamicVideoActivity extends BaseActivity {

    private EmojisEditText mEmojisEditText;
    private MaskImageView video_iv;
    private String path, screenshot_path;
    private FileMessage videoFileMessage, videoConverFileMessage;
    private ZProgressHUD zProgressHUD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_send_friend_dynamic_video;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        sendVideo();
    }

    protected void initView() {
        zProgressHUD = new ZProgressHUD(this);
        mEmojisEditText = (EmojisEditText) findViewById(R.id.send_text_et);
        video_iv = (MaskImageView) findViewById(R.id.video_iv);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.title_right_tv)).setText(R.string.send);
    }

    protected void initListener() {
        findViewById(R.id.title_right_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/3/1
                if (!TextUtils.isEmpty(screenshot_path) && !TextUtils.isEmpty(path)) {
                    findViewById(R.id.title_right_layout)
                            .setEnabled(false);
                    uploadPic(path);
                }
            }
        });

        video_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(path)) {
                    Intent intent = new Intent(SendDynamicVideoActivity.this, VideoPlayerActivity.class);
                    intent.putExtra("path", path);
                    startActivity(intent);
                }
            }
        });
    }


    /**
     * 发送视频
     */
    private void sendVideo() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        int h = 960;
        if (dm.heightPixels < 960) {
            h = dm.heightPixels;
        }
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .doH264Compress(true)
                .smallVideoWidth(480)
//                .smallVideoWidth(dm.widthPixels)
                .smallVideoHeight(360)
                .recordTimeMax(6 * 1000)
                .maxFrameRate(20)
                .minFrameRate(8)
                .captureThumbnailsTime(1)
                .recordTimeMin((int) (1.5 * 1000))
                .build();
        Intent intent = new Intent(SendDynamicVideoActivity.this, MediaRecorderActivity.class);
        intent.putExtra("media_recorder_config_key", config);
        startActivityForResult(intent, ChatRequestCodeManage.SEND_VIDEO);
//        MediaRecorderActivity.goSmallVideoRecorder(ChatActivity.this, PreviewVideoActivity.class.getName(), config);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            SendDynamicVideoActivity.this.finish();
        } else {
            if (requestCode == ChatRequestCodeManage.SEND_VIDEO) {
                //视频地址
                path = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                //视频封面地址
                screenshot_path = data.getStringExtra(MediaRecorderActivity.VIDEO_SCREENSHOT);
                Bitmap compressBitmap = ImageUtil.CompressImageSameRadioScale(screenshot_path,
                        100, 960, 960);
                video_iv.setImageBitmap(compressBitmap);
            }
        }
    }


    // 上传图片
    public void uploadPic(final String imageUrl) {
        Log.e("上传地址：", imageUrl);
        String url = APIConfiguration.getBaseUrl()
                + "Dynamic/Dynamic/sendFile?"
                + APIConfiguration.getCustIdAndToken();
        HttpRequestAsyncTaskQueue.getInstance().AddTask(
                new HttpUploadFileAsyncTask("0", imageUrl, url,
                        "uploadedFile") {

                }, new OnUploadFileListener() {

                    @Override
                    public void OnSuccess(String key, String response) {
                        FileMessage fileMessage = new FileMessage();
                        try {
                            JSONObject json = new JSONObject(response);
                            fileMessage.status = json.optInt("status");
                            JSONObject dataJson = json
                                    .optJSONObject("data");
                            if (dataJson != null) {
                                fileMessage.fileid = dataJson
                                        .optString("fileid");
                                fileMessage.filehash = dataJson
                                        .optString("filehash");
                                if (fileMessage != null
                                        && fileMessage.status == 0) {
                                    if (imageUrl.equals(path)) {
                                        // 视频上传结果
                                        videoFileMessage = fileMessage;
                                        uploadPic(screenshot_path);
                                    } else if (imageUrl.equals(screenshot_path)) {
                                        // TODO: 2017/3/1 上传封面结果
                                        videoConverFileMessage = fileMessage;
                                        sendDynamic();
                                    }
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void OnFail(String key, String reason) {
                        // TODO: 2017/3/1 上传失败
                    }
                });

    }

    public void sendDynamic() {
        zProgressHUD.show();
        String mStrContent = mEmojisEditText.getText().toString();
        DynamicHandle.sendDynamic(mStrContent, null, videoFileMessage, videoConverFileMessage, new DynamicHandle.IDynamicResult() {
            @Override
            public void onDynamicResult(int status, String msg) {
                zProgressHUD.dismiss();
                if (status == 0) {
                    setResult(RESULT_OK);
                    finish();
                } else if (!TextUtils.isEmpty(msg)) {
                    IMApplication.showToast(msg);
                    findViewById(R.id.title_right_layout)
                            .setEnabled(true);
                }
            }
        });

    }
}
